<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload files</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<style type="text/css">

.divFile{
	margin-left: 0px;
}

ul.divFile li {
	display: inline-block;
	vertical-align: bottom;
	margin: 5px;
}
button {
	height: 30px;
}
</style>
<link
	href="<c:url value="/resources/bootstrap/css/bootstrap.min.css" />"
	rel="stylesheet" media="screen">
</head>
<body>
	<h1 align="center">Upload multiple files page</h1>
	<div align="center">
		<div class="alert alert-info" align="left">
			<h4>Warning!</h4>
			The files will be saved to D:\*.
			<br/>
			The file's size limit is 2MB.
			<br/>
			The acceptable file's type is "ZIP".
		</div>
		<hr align="center" width="30%"/>
	</div>

	

	<!-- ------------------------------Main Form------------------------------------ -->
	<div style="padding-left: 200px">
		<form action="${pageContext.request.contextPath}/uploadfiles/confirm" method="post" id="uploadForm">
			<div class='divFiles' id="divFiles">
				<!-- use  javascipt to insert html here -->
			</div>
		
			<br/>
			<div class="divActions">
				<input type="button" class="btn btn-primary" value="Add another file" id="btnAddMore"/> 
				<input type="button" class="btn btn-primary" value="Upload all" id="btnUpload"/> 
			</div>
		</form>
	</div>
	<!-- ------------------------------/Main Form------------------------------------ -->

	<!-- ------------------------------JQuery------------------------------------ -->
	<script>
		
		$(document).ready(function(){
			
			// "/UploadMultipleFiles-3.0/uploadfiles"  
			var serverPath = location.pathname;
			
			// For generating HTML dynamically
			var  fileCount = 1;
			// For file size limiting
			var sizeLimit = 2;
			
			// Add the first file selector
			addMoreFile();
			
			// To upload ONE file to server and update UI
			function processUpload(fileInputId){
				if(checkFileSizeLimit(fileInputId) && checkFileType(fileInputId)){
					uploadFile(serverPath, fileInputId);
					processUploadingUI(fileInputId);
				}
			}
			
			// Check file size limit
			function checkFileSizeLimit(fileInputId){
				var fileInput = document.getElementById(fileInputId);
				var fileSize = (fileInput.files[0].size/1000/1000).toFixed(2);
				if(fileSize > sizeLimit){
					alert("The file's size is " + fileSize + "MB > " + sizeLimit + "MB, Too large!");
					return false;
				}
				return true;
			}
			
			// Check the file type
			function checkFileType(fileInputId){
				console.log(fileInputId);
				var fileInput = document.getElementById(fileInputId);
				var fileName = fileInput.files[0].name;
				console.log(fileName);
				if(fileName){
					var fileType = fileName.substring(fileName.length - 3);
					console.log(fileType);
					if(fileType != "zip"){
						alert("The file's type (" + fileType + ") is invalid. The file's type must be \"ZIP\".");
						return false;
					}
					return true;
				}
				return false;
			}			
			
			// To update UI while uploading a file
			function processUploadingUI(fileInputId){
				
				var fileInput = document.getElementById(fileInputId);
				var fileName = fileInput.files[0].name;
				var fileSize = (fileInput.files[0].size / 1000 / 1000).toFixed(2);
				
				var hdFileName = $('#' +  fileInputId).parent().parent().find('input[type="hidden"]');
				hdFileName.attr('value', fileName);
				
				$('#' +  fileInputId).replaceWith('<span class="label label-info">'+ fileName + ' - ' + fileSize +'MB</span>');
			} 
			
			// To upload one file to server by using Jquey Ajax
			function uploadFile(url, fileInputId){
				
				var grand = $('#' + fileInputId).parent().parent().parent();
				var file = document.getElementById(fileInputId).files[0];
				var formData = new FormData();
				formData.append(file.name, file);
				
	            var xhr = new XMLHttpRequest();
	            xhr.open('POST', url, true);
	            xhr.onload = function(e){
	                if (this.status == 200) {
						grand.find('button[id^="btnDelete"]').css('visibility', 'visible');
					}
	            };
	            
				var divProgress = grand.find(".divProgress"); 
	            // Listen to the upload progress.
				xhr.upload.onprogress = function(e){
	            	divProgress.css('visibility', 'visible');
					var progessBar = divProgress.find('div[id^="progressBar"]');
					if (e.lengthComputable) {
						var uploadedPercent = (e.loaded / e.total * 100).toFixed(2) + "%" ;
						progessBar.css("width", uploadedPercent);
					}
				};
	            
	            xhr.send(formData);
			}
		
			// To add another file selector by using javascript
			function addMoreFile(){
				$('#divFiles').append(
					'<ul class="divFile">'+
						'<li>'+
							'<div class="btn btn-file" style="float: left;">'+
									'File: <input type="file" id="inpFile' + fileCount + '"/>'+
							'</div>'+
							'<input type="hidden" value="" id="hdFileName'+ fileCount + '" name="hdFileName" />'+
						'</li>'+
						'<li>'+
								'<div style="float: left; width: 200px; height: 30px; visibility:hidden;" class="divProgress">'+
									'<div class="progress progress-striped active" style="height: 100%;">'+
										'<div id="progressBar' + fileCount + '" class="bar" style="width: 60%;"></div>'+
									'</div>'+
								'</div>'+
						'</li>'+
						'<li>'+
							'<button class="btn btn-danger" style="visibility:hidden;" id="btnDelete' + fileCount + '">Delete</button>'+
						'</li>'+
					'</ul>'
				);
				fileCount++;
			}
			
			// To delete a uploaded file with the given file name
			function deleteUploadedFile(url, fileName){
				var xhr = new XMLHttpRequest();
                xhr.open('POST', url, true);
                xhr.onload = function(e){
                    if (this.status == 200) {
                    }
                };
	            xhr.send(fileName);
			}
		
			// To process when a file selector is clicked
			$(':file').live('change', function() {
				processUpload(this.id);
			});
			
			// To process when the button "Add another file"  is clicked
			document.getElementById('btnAddMore').addEventListener('click', function(e){
				addMoreFile();
			}, false);
			
			// To process when a button "Delete" is clicked
	        $('button[id^="btnDelete"]').live('click', function(){
				
	            // Get <div> element that contains the clicked file field.
	            var divFileField = $(this).parent().parent();
				
				var hdFileName = divFileField.find('input[id^="hdFileName"]');
				deleteUploadedFile(serverPath + "/deletefile", hdFileName.val());
				
	            // Remove the <div> element. 
	            divFileField.remove();
	        });
			
			// To process when the button "Upload all" is clicked
			$('#btnUpload').click(function(e){
				
				$('#uploadForm').submit();
			});
		
		});
	</script>
	
	<script src="<c:url value="/resources/bootstrap/js/bootstrap.min.js" />" ></script>
	<!-- ------------------------------/JQuery------------------------------------ -->
</body>
</html>